import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/widgets/common_widgets.dart';
import 'package:gold/widgets/xfg_text.dart';

/// Descriptions: 权限弹窗，安卓下需要弹窗说明
/// User: tangzhentao
/// Date: 4:58 下午 2021/12/7
Future<bool> showRequestPermissionDialog({
  required List<Permission> permissions,
  String description = ''
}) async {
  final List<String> results = [];
  final List<Permission> deniedPermissions = [];
  await Future.forEach(permissions, (permission) async {
    final status = await permission.status;
    if (status != PermissionStatus.granted && status != PermissionStatus.denied) {
      results.add(_getPermissionDesc(permission) + _getPermissionStatusDesc(status));
    }
    if (status == PermissionStatus.denied) deniedPermissions.add(permission);
  });
  /// 有权限不能申请，给用户提示
  if (results.isNotEmpty) {
    _showDeniedSnackBar(results);
    return false;
  }
  /// 所有权限都被同意
  if (deniedPermissions.isEmpty) return true;
  /// 安卓下需要单独弹窗
  if (Platform.isAndroid) {
    _showPermissionDescDialog(description);
  }
  /// 请求权限
  final status = await deniedPermissions.request();
  bool result = true;
  status.forEach((key, status) {
    if (status != PermissionStatus.granted) {
      result = false;
      results.add(_getPermissionDesc(key) + _getPermissionStatusDesc(status));
    }
  });
  /// 有权限申请未通过，给用户提示
  if (results.isNotEmpty) _showDeniedSnackBar(results);
  return result;
}

/// 展示拒绝信息
_showDeniedSnackBar(List<String> results) {
  ScaffoldMessenger.of(XfgNav.currentContext).showSnackBar(
    SnackBar(
      content: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: results.map((result) {
          return Container(
            padding: EdgeInsets.symmetric(vertical: XfgSize().size5),
            child: XfgText(result, color: XfgColor.white, fontSize: XfgSize().text14, bold: FontWeight.bold),
          );
        }).toList(),
      ),
      backgroundColor: XfgColor.theme, showCloseIcon: true,
    ),
  );
}

/// 展示请求权限的说明弹窗
void _showPermissionDescDialog(String description) => showDialog<bool>(
  context: XfgNav.currentContext,
  barrierColor: XfgColor.transparent,
  barrierDismissible: false,
  builder: (_) => _PermissionDescDialog(description),
);

/// 返回权限描述信息
String _getPermissionDesc(Permission permission) {
  switch(permission) {
    case Permission.camera:
      return '相机权限';
    case Permission.photos:
      return '相册权限';
    case Permission.storage:
      return '存储权限';
    case Permission.location:
      return '位置权限';
    case Permission.locationWhenInUse:
      return '应用运行时位置权限';
    case Permission.locationAlways:
      return '始终位置权限';
    default:
      return '未知权限';
  }
}

/// 返回权限状态描述信息
String _getPermissionStatusDesc(PermissionStatus status) {
  switch(status) {
    case PermissionStatus.denied:
      return '已拒绝，功能可能无法正常使用';
    case PermissionStatus.limited:
      return '仅支持有限访问，请在设置中更改权限状态';
    case PermissionStatus.permanentlyDenied:
      return '已被拒绝，请在设置中更改权限状态';
    case PermissionStatus.restricted:
      return '因家长控制，无法申请';
    default:
      return '已同意';
  }
}

class _PermissionDescDialog extends StatelessWidget {
  final String description;

  const _PermissionDescDialog(this.description);

  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: Container(
        padding: EdgeInsets.only(top: XfgSize().statusBarHeight + kToolbarHeight),
        alignment: Alignment.topCenter,
        child: Container(
            width: XfgSize().size315,
            padding: EdgeInsets.all(XfgSize().size16),
            decoration: white10Decoration,
            child: XfgText(description, fontSize: XfgSize().text18, color: XfgColor.text1, height: 1.5),
        ),
      ),
    );
  }
}